import 'dart:ui';

import 'package:winkai/db/database.dart';
import 'package:winkai/helper/iap/iap_helper.dart';
import 'package:winkai/service/api_service.dart';
import 'package:winkai/entity/user_info.dart';
import 'package:winkai/ext/ext.dart';
import 'package:winkai/helper/value_helper.dart';
import 'package:winkai/utils/listerer.dart';

class UserHelper {
  static UserHelper? _singleton;

  factory UserHelper() {
    _singleton ??= UserHelper._();
    return _singleton!;
  }

  UserHelper._() {
    ValueHelper.instance.getUserInfo().then((value) {
      _userInfo = value;
    });
  }

  bool _isRegisterAccount = false;

  bool get isRegisterAccount => _isRegisterAccount;

  ///是否登录
  bool get isLogin => user.id.isNotEmpty;

  ///用户资料
  UserInfo? _userInfo;

  String get userId => user.deviceId ?? '';

  ///用户资料
  UserInfo get user {
    _userInfo ??= UserInfo();
    return _userInfo!;
  }

  Future<bool> tryRegisterAccount([bool isInit = false]) async {
    var deviceId = await ValueHelper.instance.getDeviceId();
    var userInfo = await ValueHelper.instance.getUserInfo();
    bool isRegisterAccount = false;
    if (userInfo != null && userInfo.id.isNotEmpty == true) {
      isRegisterAccount = true;
    } else {
      try {
        var result = await ApiService().registerAccount(deviceId);
        if (result.isSucceed) {
          userInfo = result.data;
          await ValueHelper.instance.savaUserInfo(userInfo);
          isRegisterAccount = true;
        }
      } catch (e) {}
    }

    var accountInfo = await rootDb.actDao.getCurrentAccount(deviceId: deviceId);
    UserInfo user = userInfo ?? UserInfo();
    if (accountInfo != null && accountInfo.id.isNotEmpty) {
      user.deviceId = accountInfo.id;
      if (accountInfo.serviceUserId?.isNotEmpty == true) {
        user.id = accountInfo.serviceUserId!;
      }
      user.avatar = accountInfo.avatar;
      user.nickname = accountInfo.nickname;
    } else {
      user.deviceId = deviceId;
    }
    await rootDb.actDao.insertOrUpdate(
      deviceId: deviceId,
      serviceUserId: userInfo?.id,
      nickname: user.nickname,
      avatar: user.avatar,
    );

    _userInfo = user;
    _isRegisterAccount = isRegisterAccount;
    if (isInit) {
      await IAPHelper().checkSubscribeStatus();
    }
    return isRegisterAccount;
  }

  final Map<String, int> _cache = {};

  final ListenerManager<int> _controller = ListenerManager();

  void refresh() async {
    final res = await rootDb.sesDao.selectUnReadUnmSum();
    update(res);
  }

  /// 更新操作
  void update(int value) {
    _cache[userId] = value;
    _controller.add(value);
  }

  /// 减去未读数量
  void subtract(int value) async {
    if (value > 0) {
      if (_cache[userId] != null) {
        value = (_cache[userId] ?? 0) - value;
      } else {
        final res = await rootDb.sesDao.selectUnReadUnmSum();
        value = res - value;
      }
      value = value > 0 ? value : 0;
      update(value);
    }
  }

  /// 增加数量
  void add(int value) async {
    if (value > 0) {
      if (_cache[userId] != null) {
        value = (_cache[userId] ?? 0) + value;
      } else {
        final res = await rootDb.sesDao.selectUnReadUnmSum();
        value = res + value;
      }
      value = value > 0 ? value : 0;
      update(value);
    }
  }

  /// 监听
  VoidCallback listener(void Function(int) onData) {
    _controller.listener(onData);
    return () => _controller.remove(onData);
  }
}
